package org.example.threadpooltaskexecutor.demos.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.PostConstruct;
import java.util.concurrent.*;

@Configuration
public class ThreadPoolConfig {

    @Bean(name = "asyncExecutor")
    public Executor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(1);         // 核心线程数
        executor.setMaxPoolSize(1);          // 最大线程数
        executor.setQueueCapacity(1);       // 队列容量
        executor.setKeepAliveSeconds(300);    // 线程空闲时间
        executor.setThreadNamePrefix("Async-"); // 线程名前缀

        // 设置拒绝策略：当线程池达到最大容量时，如何处理新任务，下面的代码时交给调用者执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        executor.initialize(); // 初始化

//线程池监控
        ScheduledExecutorService monitor = Executors.newSingleThreadScheduledExecutor();
        monitor.scheduleAtFixedRate(() -> {
            ThreadPoolExecutor tp = (ThreadPoolExecutor) executor.getThreadPoolExecutor();
            System.out.println("AsyncExecutor: Active=" + tp.getActiveCount()
                    + ", Queue=" + tp.getQueue().size()
                    + ", Completed=" + tp.getCompletedTaskCount());
        }, 0, 5, TimeUnit.SECONDS);
        return executor;
    }


}